#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unordered_map>
#include <sys/stat.h>
#include <fcntl.h>

#define COMMAND_SIZE 1024
#define FORMAT "[%s@%s %s]# "

//1.命令行参数表
#define MAXARGC 128
char* g_argv[MAXARGC];
int g_argc = 0;

//2.环境变量表
#define MAX_ENVS 100
char* g_env[MAX_ENVS];
int g_envs = 0;

//3.别名映射表
std::unordered_map<std::string, std::string> alias_list;

//4.重定向
#define NONE_REDIR 0
#define INPUT_REDIR 1
#define OUTPUT_REDIR 2
#define APPEND_REDIR 3

//默认是没有重定向
int redir = NONE_REDIR;
//重定向的文件名
//ls > log.txt
std::string filename;

//for test
char cwd[1024];
char cwdenv[1024];

//last exit code
int lastcode = 0;

const char* GetUserName()
{
    const char* name = getenv("USER");
    return name == NULL ? "none" : name;
}

const char* GetHostName()
{
    const char* hostname = getenv("HOSTNAME");
    return hostname == NULL ? "none" : hostname;
}

const char* GetPwd()
{
    //const char* pwd = getenv("PWD");
    const char* pwd = getcwd(cwd, sizeof(cwd));
    if(pwd != NULL)
    {
        snprintf(cwdenv, sizeof(cwdenv), "PWD=%s", cwd);
        putenv(cwdenv);
    }
    return pwd == NULL ? "none" : pwd;
}

const char* GetHome()
{
    const char* home = getenv("HOME");
    return home == NULL ? "" : home;
}

void InitEnv()
{
    extern char** environ;
    //将环境变量表初始化
    memset(g_env, 0, sizeof(g_env));
    g_envs = 0;
    
    //1.利用environ获取环境变量
    for(int i = 0; environ[i]; i++)
    {
        //使用动态开辟的方法
        g_env[i] = (char*)malloc(strlen(environ[i]) + 1);
        strcpy(g_env[i], environ[i]);
        g_envs++;
    }

    g_env[g_envs] = NULL;
    
    //2.导成环境变量
    for(int i = 0; g_env[i]; i++)
    {
        putenv(g_env[i]);
    }
    environ = g_env;
}

//清理动态开辟的资源
void clean()
{
    for(int i = 0; g_env[i]; i++)
    {
        free(g_env[i]);
        g_env[i] = NULL;
    }
}

//command
bool Cd()
{
    //指令cd 就是回到家目录
    if(g_argc == 1)
    {
        std::string home = GetHome();
        if(home.empty()) return true;
        chdir(home.c_str());
    }
    else
    {
        std::string where = g_argv[1];
        chdir(where.c_str());
    }
    return true;
}

void Echo()
{
    std::string opt = g_argv[1];
    if(g_argc == 2)
    {
        //echo $?
        //echo $PATH
        //std::string opt = g_argv[1];
        if(opt == "$?")
        {
            std::cout << lastcode << std::endl;
            lastcode = 0;
        }
        else if(opt[0] == '$')
        {
            std::string env_name = opt.substr(1);
            const char* env_value = getenv(env_name.c_str());
            if(env_value)
                std::cout << env_value << std::endl;
        }
    }
    else{
        //echo "hello world"
        int i = 2;
        while(g_argv[i] != NULL)
        {
            opt += " ";
            opt += g_argv[i++];
        } 
        //printf("%s\n", g_argv[0]);
        //printf("%s\n", g_argv[1]);
        std::cout << opt << std::endl;
    }
}

//缩短工作路径的名字
std::string DirName(const char* pwd)
{
#define SLASH "/"
    std::string dir = pwd;
    if(dir == SLASH) return SLASH;
    //rfind -> 反向查询
    auto pos = dir.rfind(SLASH);
    if(pos == std::string::npos) return "BUG";
    return dir.substr(pos + 1);

}

void MakeCommandLine(char cmd_prompt[], int size)
{
    snprintf(cmd_prompt, size, FORMAT, GetUserName(), GetHostName(), DirName(GetPwd()).c_str());
    //snprintf(cmd_prompt, size, FORMAT, GetUserName(), GetHostName(), GetPwd());
}

void PrintCommandPrompt()
{
    char prompt[COMMAND_SIZE];
    MakeCommandLine(prompt, sizeof(prompt));
    printf("%s", prompt);
    fflush(stdout);
}

bool GetCommandLine(char* out, int size)
{
    char *c = fgets(out, size, stdin);
    if(c == NULL) return false;
    out[strlen(out) - 1] = 0; //清理\n
    if(strlen(out) == 0) return false;
    return true;
}

bool CommandParse(char* commandline)
{
#define SEP " "
    g_argc = 0;
    //分割字符串
    g_argv[g_argc++] = strtok(commandline, SEP);
    while(g_argv[g_argc++] = strtok(nullptr, SEP));
    g_argc--;
    return true;
}

void PrintArgv()
{
    for(int i = 0; g_argv[i]; i++)
    {
        printf("argv[%d]->%s\n", i, g_argv[i]);
    }
    printf("argc: %d\n", g_argc);
}


bool CheckAndExecBuiltin()
{
    std::string cmd = g_argv[0];
    if(cmd == "cd")
    { 
        Cd();
        return true;
    }
    else if(cmd == "echo")
    {
        Echo();
        return true;
    }
    //else export alias
    return false;
}

int Execute()
{
    pid_t id = fork();
    if(id == 0)
    {
        int fd = - 1;
        //输入重定向 -> 只读
        if(redir == INPUT_REDIR)
        {
            fd = open(filename.c_str(), O_RDONLY);
            if(fd < 0) exit(1);
            dup2(fd, 0);
            close(fd);
        }
        //输出重定向 -> 创造 写入 清除
        else if(redir == OUTPUT_REDIR)  
        {
            fd = open(filename.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
            if(fd < 0) exit(2);
            dup2(fd, 1);
            close(fd);
        }
        //追加重定向 -> 创造 写入 追加
        else if(redir == APPEND_REDIR)
        {
            fd = open(filename.c_str(), O_CREAT | O_WRONLY | O_APPEND, 0666);
            if(fd < 0) exit(2);
            dup2(fd, 1);
            close(fd);
        }
        
        //进程替换
        execvp(g_argv[0], g_argv);
        exit(1);
    }

    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if(rid > 0)
    {
        lastcode = WEXITSTATUS(status);
    }
    return 0;
}

//跳过空格的功能
void TrimSpace(char cmd[], int &end)
{
    while(cmd[end] == ' ') end++;
}

void RedirCheck(char cmd[])
{
    //清理下上次的重定向的方式和文件名
    redir = NONE_REDIR;
    filename.clear();

    //"ls -a -l >> file.txt" > >> <
    int start = 0, end = strlen(cmd) - 1;
    //倒着找 < >> < 等字符
    while(end > start)
    {
        //输入重定向
        if(cmd[end] == '<')
        {
            //分割出后面的文件名
            cmd[end++] = 0;
            TrimSpace(cmd, end);
            redir = INPUT_REDIR;
            filename = cmd + end;
            break;
        }
        else if(cmd[end] == '>')
        {
            //判断是输出重定向还是追加重定向
            if(cmd[end-1] == '>') 
            {
                cmd[end-1] = 0;
                redir = APPEND_REDIR;
            }
            else{
                redir = OUTPUT_REDIR;
            }

            cmd[end++] = 0;
            TrimSpace(cmd, end);
            filename = cmd + end;
            break;
        }
        else
        {
            end--;
        }
    }

}


int main()
{
    //printf("[%s@%s %s]# \n", GetUserName(), GetHostName(), GetPwd());
    //printf("%s\n", GetHostName());
    InitEnv();

    while(true)
    {
        //1. 输出命令行提示符
        PrintCommandPrompt();

        //2.获取用户输入的命令
        char commandline[COMMAND_SIZE];     //获取输入的命令及其选项
        if(!GetCommandLine(commandline, sizeof(commandline)))
            continue;

        //3.重定向分析"ls -a -l > file.txt" -> "ls -a -l" "file.txt"
        //分割出指令和重定向的文件名，同时判断出重定向的方式
        RedirCheck(commandline);

        //4.分析命令 "ls -a -l"
        if(!CommandParse(commandline))
            continue;
        //PrintArgv();

        //5.检测并处理内建命令
        if(CheckAndExecBuiltin())
            continue;

        //6.利用进程替换执行命令
        Execute(); 
    }
    clean();
    return 0;
}